<script setup lang="ts">
import { NForm, NFormItem, NDynamicInput, NInput, NButton, NSelect, NRow, FormInst, useMessage } from 'naive-ui'
import { ref } from 'vue';
import { runCrawler } from '../api/crawler'

const $message = useMessage()

interface ModelType {
  method: string
  url: string
  cssSelector: string
  regularSelector: string
  headers: any[]
}

const reqRes = ref<any>() // 请求结果
const formRef = ref<FormInst | null>()

const model = ref<ModelType>(localStorage.getItem('crawlerModel') ? JSON.parse(localStorage.getItem('crawlerModel')!) :{
  method: 'GET',
  url: 'https://www.manhua666.cc/12_12036/',
  cssSelector: '',
  regularSelector: '',
  headers: [],
})

const formRules = ref({
  url: {
    required: true,
    message: '请输入URL',
    trigger: 'blur'
  },
  method: {
    required: true,
    message: '请选择请求方法',
    trigger: 'change'
  }
})

const methodOptions = [
  { label: 'GET', value: 'GET' },
  { label: 'POST', value: 'POST' }
]

async function getCrawlerRes() {
  try {
    localStorage.setItem('crawlerModel', JSON.stringify(model.value))
    const headers: any = {}
    model.value.headers.forEach(h => headers[h.key] = h.value)
    const res = await runCrawler({ ...model.value, headers })
    console.log(res)
    if (res.code !== 200) throw new Error(JSON.stringify(res))
    reqRes.value = res.data
    $message.success('请求成功')
  } catch (error) {
    console.log(error);
    $message.error('请求失败')
  }
}

function resetForm() {
  formRef.value?.restoreValidation()
}
</script>

<template>
  <div class="Crawler">
    <n-form ref="formRef" :model="model" :rules="formRules">
      <n-form-item path="method" label="method">
        <n-select v-model:value="model.method" :options="methodOptions" />
      </n-form-item>
      <n-form-item path="url" label="要爬取的连接">
        <n-input v-model:value="model.url" @keydown.enter.prevent />
      </n-form-item>
      <n-form-item path="headers" label="headers">
        <n-dynamic-input v-model:value="model.headers" preset="pair" key-placeholder="请求头key" value-placeholder="请求头值" />
      </n-form-item>
      <n-form-item path="cssSelector" label="CSS选择器筛选">
        <n-input v-model:value="model.cssSelector" @keydown.enter.prevent />
      </n-form-item>
      <n-form-item path="regularSelector" label="正则表达式筛选">
        <n-input v-model:value="model.regularSelector" @keydown.enter.prevent />
      </n-form-item>
    </n-form>
    <n-row justify-content="flex-end">
      <n-button type="primary" @click="getCrawlerRes">开始爬取</n-button>
      <n-button @click="resetForm">重置</n-button>
    </n-row>
    <pre>{{ reqRes }}</pre>
  </div>
</template>

<style scoped>
.Crawler {
  padding: 0.5rem;
}
</style>
